import React, { useMemo } from 'react';
import { 
  Card, 
  Tabs, 
  Empty, 
  Spin, 
  Typography, 
  Row, 
  Col, 
  Statistic,
  Button,
  Space,
  Alert
} from 'antd';
import {
  BugOutlined,
  BarChartOutlined,
  ExclamationCircleOutlined,
  InfoCircleOutlined,
  CheckCircleOutlined,
  PlayCircleOutlined
} from '@ant-design/icons';
import { useAnalysisContext, useAnalysisActions } from '../../context/AnalysisContext';
import ProblemTable from './ProblemTable';
import './AnalysisResults.css';

const { Text, Title } = Typography;

const RuleAnalysisResults: React.FC = () => {
  const { state } = useAnalysisContext();
  const actions = useAnalysisActions();

  const {
    analysisResult,
    isAnalyzing,
    sqlContent,
    sourceDbType,
    targetDbType,
    activeTab,
    selectedIssueId
  } = state;

  // 分析统计数据
  const statistics = useMemo(() => {
    if (!analysisResult?.statistics) return null;
    
    const stats = analysisResult.statistics;
    return {
      total: stats.totalIssues || 0,
      high: stats.highSeverityCount || 0,
      medium: stats.mediumSeverityCount || 0,
      low: stats.lowSeverityCount || 0,
      info: stats.infoCount || 0,
      categories: {
        syntax: stats.categoryCounts?.SYNTAX || 0,
        function: stats.categoryCounts?.FUNCTION || 0,
        datatype: stats.categoryCounts?.DATATYPE || 0,
        performance: stats.categoryCounts?.PERFORMANCE || 0
      }
    };
  }, [analysisResult]);

  // 分组后的问题列表
  const groupedProblems = useMemo(() => {
    if (!analysisResult?.issues) return [];

    const issues = analysisResult.issues;
    
    return [
      {
        key: 'HIGH',
        title: '高危问题',
        icon: <ExclamationCircleOutlined style={{ color: '#ff4d4f' }} />,
        count: issues.filter(i => i.severity === 'HIGH').length,
        items: issues.filter(i => i.severity === 'HIGH'),
        color: '#ff4d4f'
      },
      {
        key: 'MEDIUM',
        title: '中危问题',
        icon: <ExclamationCircleOutlined style={{ color: '#faad14' }} />,
        count: issues.filter(i => i.severity === 'MEDIUM').length,
        items: issues.filter(i => i.severity === 'MEDIUM'),
        color: '#faad14'
      },
      {
        key: 'LOW',
        title: '低危问题',
        icon: <InfoCircleOutlined style={{ color: '#1890ff' }} />,
        count: issues.filter(i => i.severity === 'LOW').length,
        items: issues.filter(i => i.severity === 'LOW'),
        color: '#1890ff'
      },
      {
        key: 'INFO',
        title: '提示信息',
        icon: <InfoCircleOutlined style={{ color: '#52c41a' }} />,
        count: issues.filter(i => i.severity === 'INFO').length,
        items: issues.filter(i => i.severity === 'INFO'),
        color: '#52c41a'
      }
    ].filter(group => group.count > 0);
  }, [analysisResult]);

  // 处理问题点击
  const handleIssueClick = (issue: any) => {
    actions.setSelectedIssueId(issue.id);
    actions.setCursorPosition({ 
      line: issue.lineNumber, 
      column: issue.columnNumber 
    });
  };

  // 处理Tab切换
  const handleTabChange = (key: string) => {
    actions.setActiveTab(key);
  };

  // 渲染统计卡片
  const renderStatistics = () => {
    if (!statistics) return null;

    return (
      <div className="analysis-stats">
        <Row gutter={16}>
          <Col span={6}>
            <Statistic
              title="问题总数"
              value={statistics.total}
              valueStyle={{ color: statistics.total > 0 ? '#ff4d4f' : '#52c41a' }}
              prefix={<BugOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="高危"
              value={statistics.high}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="中危"
              value={statistics.medium}
              valueStyle={{ color: '#faad14' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="低危"
              value={statistics.low}
              valueStyle={{ color: '#1890ff' }}
            />
          </Col>
        </Row>
      </div>
    );
  };

  // 渲染空状态
  const renderEmptyState = () => {
    if (!sqlContent.trim()) {
      return (
        <div className="analysis-empty">
          <div className="analysis-empty-icon">
            <BugOutlined />
          </div>
          <div className="analysis-empty-text">
            请在左侧编辑器中输入SQL语句
          </div>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            支持Oracle、MySQL、PostgreSQL等多种数据库
          </Text>
        </div>
      );
    }

    if (sourceDbType === targetDbType) {
      return (
        <div className="analysis-empty">
          <div className="analysis-empty-icon">
            <InfoCircleOutlined />
          </div>
          <div className="analysis-empty-text">
            源数据库和目标数据库相同
          </div>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            请选择不同的数据库类型进行兼容性分析
          </Text>
        </div>
      );
    }

    return (
      <div className="analysis-empty">
        <div className="analysis-empty-icon">
          <PlayCircleOutlined />
        </div>
        <div className="analysis-empty-text">
          点击"规则分析"按钮开始分析
        </div>
        <Text type="secondary" style={{ fontSize: '12px' }}>
          基于预定义规则检测兼容性问题
        </Text>
      </div>
    );
  };

  // 渲染成功状态
  const renderSuccessState = () => (
    <div className="analysis-empty">
      <div className="analysis-empty-icon" style={{ color: '#52c41a' }}>
        <CheckCircleOutlined />
      </div>
      <div className="analysis-empty-text">
        恭喜！未发现兼容性问题
      </div>
      <Text type="secondary" style={{ fontSize: '12px' }}>
        您的SQL语句可以直接在目标数据库中使用
      </Text>
    </div>
  );

  // Tab配置
  const tabItems = [
    {
      key: 'issues',
      label: (
        <Space>
          <BugOutlined />
          兼容性问题
          {statistics && statistics.total > 0 && (
            <span className="tab-badge">{statistics.total}</span>
          )}
        </Space>
      ),
      children: (
        <div className="problems-container">
          {groupedProblems.length > 0 ? (
            <ProblemTable
              problems={groupedProblems}
              selectedIssueId={selectedIssueId}
              onIssueClick={handleIssueClick}
            />
          ) : (
            renderSuccessState()
          )}
        </div>
      )
    },
    {
      key: 'statistics',
      label: (
        <Space>
          <BarChartOutlined />
          分析统计
        </Space>
      ),
      children: (
        <div className="statistics-container">
          {statistics ? (
            <div>
              {renderStatistics()}
              
              <div style={{ marginTop: 16 }}>
                <Title level={5}>问题分类统计</Title>
                <Row gutter={[16, 16]}>
                  <Col span={12}>
                    <Statistic
                      title="语法问题"
                      value={statistics.categories.syntax}
                      suffix="个"
                    />
                  </Col>
                  <Col span={12}>
                    <Statistic
                      title="函数问题"
                      value={statistics.categories.function}
                      suffix="个"
                    />
                  </Col>
                  <Col span={12}>
                    <Statistic
                      title="数据类型问题"
                      value={statistics.categories.datatype}
                      suffix="个"
                    />
                  </Col>
                  <Col span={12}>
                    <Statistic
                      title="性能问题"
                      value={statistics.categories.performance}
                      suffix="个"
                    />
                  </Col>
                </Row>
              </div>
            </div>
          ) : (
            <Empty description="暂无统计数据" />
          )}
        </div>
      )
    }
  ];

  return (
    <Card 
      className="results-section"
      title={
        <Space>
          <BugOutlined />
          <span>规则分析结果</span>
          {isAnalyzing && <Spin size="small" />}
        </Space>
      }
      size="small"
    >
      {isAnalyzing ? (
        <div className="analysis-loading">
          <Spin size="large" />
          <div style={{ marginTop: 16 }}>
            <Text>正在进行规则分析...</Text>
          </div>
        </div>
      ) : analysisResult ? (
        <div>
          {statistics && statistics.total > 0 && (
            <Alert
              message={`发现 ${statistics.total} 个兼容性问题`}
              description={`其中高危问题 ${statistics.high} 个，中危问题 ${statistics.medium} 个，建议及时处理`}
              type={statistics.high > 0 ? 'error' : statistics.medium > 0 ? 'warning' : 'info'}
              showIcon
              style={{ marginBottom: 16 }}
            />
          )}
          
          <Tabs
            activeKey={activeTab}
            onChange={handleTabChange}
            items={tabItems}
            size="small"
          />
        </div>
      ) : (
        renderEmptyState()
      )}
    </Card>
  );
};

export default RuleAnalysisResults;